package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.exception.AuthException;
import cn.stylefeng.guns.base.auth.exception.enums.AuthExceptionEnum;
import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.weixin.SceneData;
import cn.stylefeng.guns.sys.modular.system.model.weixin.Ticket;
import cn.stylefeng.guns.sys.modular.system.model.weixin.WxLogin;
import cn.stylefeng.guns.sys.modular.system.service.BtyWxService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信扫码登录Controller
 */
@Controller
@RequestMapping("/wxLogin")
public class WxLoginController {

    private String PREFIX = "/modular/system/";

    @Autowired
    private BtyWxService btyWxService;
    @Resource
    private DictService dictService;
    @Autowired
    private AuthService authService;

    // 临时二维码
    private final static String QR_SCENE = "QR_SCENE";
    // 临时二维码(字符串)
    private final static String QR_STR_SCENE = "QR_STR_SCENE";
    // 永久二维码
    private final static String QR_LIMIT_SCENE = "QR_LIMIT_SCENE";
    // 永久二维码(字符串)
    private final static String QR_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";
    // 生成ticket
    private String ticketPath = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    // 通过ticket换取二维码
    private String qrcodePath = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
    // 获取code
    private String codePath = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx373650bf8de7f27d&redirect_uri=";
    // 获取openId
    private String openIdPath = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx373650bf8de7f27d&secret=d3e9c259a6dbca1c5ef73beb1804f3c7&code=";


    /**
     * 生成微信二维码
     */
    @GetMapping("repayment")
    public String repayment(ModelMap model) {

        //获取accessToken
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }

        //扫码登录
        WxLogin wxLogin = new WxLogin();
        wxLogin.setAction_name(QR_SCENE);//临时二维码
        wxLogin.setExpire_seconds(60 * 5);//二维码有效时间，以秒为单位


        //场景值
        Map<String, SceneData> map = new HashMap<>();

        //二维码详细信息
        SceneData sceneData = new SceneData();
        sceneData.setScene_id(11);//场景值id
        map.put("scene_id",sceneData);

        wxLogin.setAction_info(map);//二维码详细信息


        RestTemplate restTemplate = new RestTemplate();
        JSONObject weiMsg = (JSONObject) JSONObject.toJSON(wxLogin);
        //生成ticket
        ResponseEntity<Ticket> ticketMsg = restTemplate.postForEntity(ticketPath + accessToken,weiMsg, Ticket.class);

        //获取ticket
        String ticket = ticketMsg.getBody().getTicket();

        String url = ticketMsg.getBody().getUrl();

        String ticketUrl = null;
        try {
            ticketUrl = URLEncoder.encode(ticket,"UTF-8");

            System.out.println(URLEncoder.encode("中国", "utf-8")+"=====");
            System.out.println(URLEncoder.encode(ticket, "utf-8")+"-----");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(ticketUrl);
        System.out.println("url"+qrcodePath + ticketUrl);
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        restTemplate.setMessageConverters(Collections.singletonList(converter));
        //获取二维码
        //String urlMsg = restTemplate.getForObject(qrcodePath + ticketUrl, String.class);
        byte[] bytes = new RestTemplate().getForObject(qrcodePath + ticketUrl,byte[].class);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        File file = new File("D:/pictureUpload/project/ewm.jpg");
        try {
            BufferedImage img = ImageIO.read(bais);
            ImageIO.write(img, "jpg", file);
        } catch (IOException e) {
         e.getMessage();
        }
        //将二维码信息转化为相应的JSONObject对象
//        JSONObject msgJson = JSONObject.parseObject(urlMsg);
//        System.out.println(msgJson + "+++++++++");
        String fullImgpath = "/pictureUpload/project/ewm.jpg";
        model.put("ticketMsg", ticketMsg);

        model.put("token", accessToken);

        model.put("weiMsg", weiMsg);
        model.put("urlMsg", fullImgpath);
        model.put("url", url);


       // return ticket;
        return PREFIX + "login.html";
    }


    /**
     * 生成二维码code
     * @return
     */
    @GetMapping("scanning")
    public String scanning(HttpServletRequest request,  HttpServletResponse response) throws IOException {

        //授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
        String redirect_uri = "http://rs.bantianyaozg.com/good/MP_verify_lcASwdWqj1qcSlSc.txt";

        try {
            redirect_uri = URLEncoder.encode(redirect_uri,"UTF-8");

            System.out.println(redirect_uri+"++");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //返回类型，请填写code
        String response_type = "code";
        //应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid）
        String scope = "snsapi_base";
        //重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
        String state = "123";
        //无论直接打开还是做页面302重定向时候，必须带此参数
        String wechat_redirect = "#wechat_redirect";


        RestTemplate restTemplate = new RestTemplate();

        String url = codePath + redirect_uri + "&response_type=" + response_type + "&scope=" + scope + "&state=" + state + wechat_redirect;
        //获取code
        String urlMsg = restTemplate.getForObject(url, String.class);

//        //重定向到授权页面
//        response.sendRedirect(url);

//        String code = request.getParameter("code");
//        System.out.println(code + "====");
//
//        JSONObject msgJson = JSONObject.parseObject(urlMsg);
//
//       //获取code
//        String code = msgJson.getString("code");
//
//        //填写为authorization_code
//        String grant_type = "authorization_code";
//
//        //获取access_token和openID
//        String openIdMsg = restTemplate.getForObject(openIdPath + code + "&grant_type=" + grant_type , String.class);
//
//        JSONObject openIdJson = JSONObject.parseObject(openIdMsg);
//
//        //获取openID
//        String openId = openIdJson.getString("openid");
//
//
//        System.out.println(urlMsg);
//
//       // return urlMsg;
        return PREFIX + "scanning.html";
    }

    /**
     * 获取openID
     * @return
     */
    @GetMapping("getOpenId")
    public SuccessResponseData getOpenId(HttpServletRequest request, HttpServletResponse response){
        //通过code换取网页授权access_token

        //从request里面获取code参数(当微信服务器访问回调地址的时候，会把code参数传递过来)
        //String code = request.getParameter("code");

        //System.out.println("code:"+code);

        String code = "081WaBll257vz54adcml2fop473WaBl8";

        //填写为authorization_code
        String grant_type = "authorization_code";

        RestTemplate restTemplate = new RestTemplate();

        //获取access_token和openID
           String openIdMsg = restTemplate.getForObject(openIdPath + code + "&grant_type=" + grant_type , String.class);

          JSONObject openIdJson = JSONObject.parseObject(openIdMsg);

        //获取openID
            String openId = openIdJson.getString("openid");
        System.out.println(openId+"====");

        //查询数据库中是否存在此人
        User user = btyWxService.selectUser(openId);

        String token;
        // 账号不存在
        if (user == null){
            throw new AuthException(AuthExceptionEnum.USERNAME_PWD_ERROR);
        }else {
            //登录并创建token
            token = authService.login(user.getAccount());
        }

       // return openId;
        return new SuccessResponseData(token);
    }

}
